<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		body{
			margin: 0;
		}
		#smallBox{
			width: 400px;
			height: 255px;
			position: relative;
			margin: 0 auto;
			padding: 20px;
			border: 1px solid;
		}

		#floatBox{
			width: 160px;
			height: 120px;
			background: rgba(0,0,0,.1);
			position: absolute;
			top: 0;
			left: 0;
			display: none;
		}
		#bigBox{
			width: 400px;
			height: 255px;
			overflow: hidden;
			display: none;
			position: relative;
		}
		#bigBox img{
			position: absolute;
			top: 0;
			left: 0;
		}
	</style>
</head>
<body>
	<div id="smallBox">
		<div id="floatBox"></div>
		<img src="img/small.jpg" alt="">
	</div>
	<div id="bigBox">
		<img src="img/big.jpg" alt="">
	</div>
	<script>
		(function(){
			var smallBox = document.getElementById('smallBox');
			var bigBox = document.getElementById('bigBox');
			var floatBox = document.getElementById('floatBox');
			var bigImg = bigBox.getElementsByTagName('img')[0];

			smallBox.onmouseenter = function(){
				bigBox.style.display = "block";
				floatBox.style.display = "block";
			}
			smallBox.onmouseleave = function(){
				bigBox.style.display = 'none';
				floatBox.style.display = "none";
			}
			smallBox.onmousemove = function(event){
				var e = event || window.event;

				var left = e.clientX - floatBox.offsetWidth/2 - smallBox.offsetLeft;
				var top = e.clientY - floatBox.offsetHeight/2 - smallBox.offsetTop;
				// console.log(left);
				if(left<0){
					left = 0;
				}else if(left>smallBox.offsetWidth-floatBox.offsetWidth){
					left = smallBox.offsetWidth-floatBox.offsetWidth;
				}
				if(top<0){
					top = 0;
				}else if(top>smallBox.offsetHeight - floatBox.offsetHeight){
					top = smallBox.offsetHeight - floatBox.offsetHeight;
				}
				floatBox.style.left = left + "px";
				floatBox.style.top = top + "px";

				bigImg.style.left = -floatBox.offsetLeft/smallBox.offsetWidth*bigImg.offsetWidth + "px";
				bigImg.style.top = -floatBox.offsetTop/smallBox.offsetHeight*bigImg.offsetHeight + "px";
			}

		}())

	</script>
</body>
</html>